package com.qingrongby.shop.core.interceptors;

import com.auth0.jwt.interfaces.Claim;
import com.qingrongby.shop.core.LocalUser;
import com.qingrongby.shop.util.JwtTokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @CLASSNAME PermissionInterceptor
 * @DESCRIPTION TODO
 * @AUTHOR hzp
 * @DATE 2020/7/15
 * @VERSION 1.0
 **/
public class PermissionInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ScopeLevel scopeLevel = this.getScopeLevel(handler);
        if(scopeLevel==null){
            return  true;
        }
        String token=request.getHeader("Authorizaly");
        Map<String, Claim> map= JwtTokenUtil.verifierToken(token);
        this.setToThreadLocalUser(map);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    private ScopeLevel getScopeLevel(Object object){
        if(object instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod)object;
            ScopeLevel scopeLevel=handlerMethod.getMethod().getAnnotation(ScopeLevel.class);
            return scopeLevel;
        }
        return null;
    }

    /**处理全局的user对象
     * @param map
     *@return
     *@author hzp
     *@date  2020/7/24
     */
    private void setToThreadLocalUser(Map<String, Claim> map){
        Claim scopeLevl=map.get("scope");
        Claim uid = map.get("uid");
        LocalUser.set(map);
    }
}
